package fr.uniscol.editors;

import fr.uniscol.model.EtablissementModel;
import fr.uniscol.service.IEtablissementService;
import java.beans.PropertyEditorSupport;

public class EtablissementPropertyEditor extends PropertyEditorSupport {

    private IEtablissementService etablissementService;

    public EtablissementPropertyEditor(IEtablissementService etablissementService){
        this.etablissementService = etablissementService;
    }
    
    public IEtablissementService getEtablissementService() {
        return etablissementService;
    }

    public void setEtablissementService(IEtablissementService etablissementService) {
        this.etablissementService = etablissementService;
    }
    
	@Override
	public String getAsText() {
        
        EtablissementModel etab = (EtablissementModel) getValue();
        if(etab == null){
            return "0";
        }else{
            return etab.getId() + "";
        }
	}

	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		
		long etabId = 0;
        try{
            etabId = Long.parseLong(text);
            
            if(etabId == 0){
                setValue(null);
                
            }else{
                EtablissementModel etab = etablissementService.getEtablissementById(etabId);
                System.out.println("EtabProperty:" + etab);
                setValue(etab);
            }
            
        }catch(NumberFormatException e){
            setValue(null);
        }
	}

}
